#define _CRT_SECURE_NO_WARNINGS 1
#include "Heap.h"
void HeapInit(hp* php) {
	assert(php);
	php->a = NULL;
	php->size = 0;
	php->capacity = 0;
}
void HeapDistory(hp* php) {
	assert(php);
	free(php->a);
	php->a = NULL;
	php->size = 0;
	php->capacity = 0;
}
void Swap(Heaptypedate* a, Heaptypedate* b) {
	Heaptypedate tmp = *a;
	*a = *b;
	*b = tmp;
}
void AdjustUp(Heaptypedate* a, int child) {
	assert(a);
	int parent = (child - 1) / 2;
	while (child > 0) {
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (parent - 1) / 2;
		}
		else
			break;
	}
}
void HeapPush(hp* php , Heaptypedate x) {
	assert(php);
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		Heaptypedate* tmp = (Heaptypedate*)realloc(php->a, newcapacity * sizeof(Heaptypedate));
		if (tmp == NULL)
		{
			perror("realloc:");
			exit(-1);
		}
		php->a = tmp;
		php->capacity = newcapacity;
	}
	php->a[php->size] = x;
	php->size++;
	AdjustUp(php->a, php->size - 1);
}
void AdjustDown(Heaptypedate* a, int size, int parent) {
	assert(a);
	int child = parent * 2 + 1;
	while (child <= size - 1) {
		if (child + 1 < size && a[child + 1] < a[child])
		{
			child++;
		}
		if (a[parent] > a[child])
		{
			Swap(&a[parent], &a[child]);
			parent = child;
			child = child * 2 + 1;
		}
		else
			break;
	}
}
void HeapPop(hp* php) {
	assert(php);
	assert(php->size);
	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;
	AdjustDown(php->a, php->size, 0);
}
Heaptypedate HeapTop(hp* php) {
	assert(php);
	return php->a[0];
}
bool HeapEmpty(hp* php) {
	assert(php);
	return php->size == 0;
}
int HeapSize(hp* php) {
	assert(php);
	return php->size;
}